
from django.contrib.auth.hashers import make_password
from rest_framework import status
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, RetrieveModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from user.models import VerifyCode, User
from user.serializers import SmsSerializer, RegisterSerializer, UserSerializer
from utils.send_sms import send_sms


class SmsViewSet(CreateModelMixin, GenericViewSet):
    serializer_class = SmsSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        phone = serializer.validated_data['phone']
        json = send_sms(phone)
        if json.get('code') == 200:
            vc = VerifyCode.objects.create(phone=phone, code=json.get('obj'))
            if vc:
                return Response(serializer.data, status=200)
        else:
            return Response({'msg': '验证码发送失败', 'err_code': json.get('code')}, status=200)


class UserViewSet(CreateModelMixin, UpdateModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = User.objects.all()
    # serializer_class = RegisterSerializer
    # 局部添加认证
    authentication_classes = [BasicAuthentication, SessionAuthentication, JSONWebTokenAuthentication]
    # permission_classes = [IsAuthenticated]

    def get_permissions(self):
        if self.action == 'create':
            return []
        return [IsAuthenticated()]

    def get_serializer_class(self):
        if self.action == 'create':
            return RegisterSerializer
        return UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['password'] = \
            make_password(password=serializer.validated_data['password'])
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()
